package org.easy.liblibai;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import org.easy.core.exception.BizRuntimeException;
import org.easy.core.util.HttpUtil;
import org.easy.liblibai.dto.LibLibGenerateParams;
import org.easy.liblibai.dto.LibLibImg2ImgParams;
import org.easy.liblibai.dto.LibLibTxt2ImgParams;
import org.easy.liblibai.dto.common.LibLibBaseResponse;
import org.easy.liblibai.dto.common.LibLibGenerateStatusResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 通用方法封装工具类
 */
@Slf4j
public class LibLibAiClient {
    private static final String baseUrl = "https://openapi.liblibai.cloud";

    public LibLibAiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    private final String accessKey;
    private final String secretKey;


    interface Uri {
        /**
         * 旗舰版F.1文生图
         */
        String text2imgUltra = "/api/generate/webui/text2img/ultra";


        /**
         * 旗舰图生图
         */
        String img2imgUltra = "/api/generate/webui/img2img/ultra";

        /**
         * 文生图
         */
        String text2img = "/api/generate/webui/text2img";

        /**
         * 图生图
         */
        String img2img = "/api/generate/webui/img2img";

        /**
         * 查询生图结果
         */
        String status = "/api/generate/webui/status";
    }

    private String getUrl(String uri) {
        return LibLibAiClient.baseUrl + uri;
    }


    /**
     * @param libLibGenerateParams 生图任务uuid，使用该uuid查询生图进度
     * @return
     */
    public String text2imgUltra(LibLibGenerateParams libLibGenerateParams) {
        String fullUrl = generateFullUrl(Uri.text2imgUltra);

        Map<String, Object> body = new HashMap<>();
        body.put("templateUuid", "5d7e67009b344550bc1aa6ccbfa1d7f4");
        body.put("generateParams", libLibGenerateParams);

        log.info("text2imgUltra  fullUrl:{}   body:{}", fullUrl, JSON.toJSONString(body));
        Long startTime = System.currentTimeMillis();
        String string = HttpUtil.postJson(fullUrl, null, body);
        log.info("text2imgUltra timeuse {} ms  data {}", System.currentTimeMillis() - startTime, string);
        LibLibBaseResponse<Map<String, String>> response = JSON.parseObject(string, new TypeReference<LibLibBaseResponse<Map<String, String>>>() {
        });
        if (response.getCode() != 0) {
            throw new BizRuntimeException(response.getMsg());
        }
        return response.getData().get("generateUuid");
    }


    public String img2imgUltra(LibLibGenerateParams libLibGenerateParams) {
        String fullUrl = generateFullUrl(Uri.img2imgUltra);

        Map<String, Object> body = new HashMap<>();
        body.put("templateUuid", "07e00af4fc464c7ab55ff906f8acf1b7");
        body.put("generateParams", libLibGenerateParams);

        String string = HttpUtil.postJson(fullUrl, null, body);
        LibLibBaseResponse<Map<String, String>> response = JSON.parseObject(string, new TypeReference<LibLibBaseResponse<Map<String, String>>>() {
        });
        if (response.getCode() != 0) {
            throw new BizRuntimeException(response.getMsg());
        }
        return response.getData().get("generateUuid");
    }


    public String text2imgAdvance(LibLibTxt2ImgParams params) {
        String fullUrl = generateFullUrl(Uri.text2img);

        Map<String, Object> body = new HashMap<>();
        body.put("templateUuid", "e10adc3949ba59abbe56e057f20f883e");
        body.put("generateParams", params);

        String string = HttpUtil.postJson(fullUrl, null, body);
        LibLibBaseResponse<Map<String, String>> response = JSON.parseObject(string, new TypeReference<LibLibBaseResponse<Map<String, String>>>() {
        });
        if (response.getCode() != 0) {
            throw new BizRuntimeException(response.getMsg());
        }
        return response.getData().get("generateUuid");
    }

    public String img2imgAdvance(LibLibImg2ImgParams params) {
        String fullUrl = generateFullUrl(Uri.img2img);

        Map<String, Object> body = new HashMap<>();
        body.put("templateUuid", "9c7d531dc75f476aa833b3d452b8f7ad");
        body.put("generateParams", params);

        String string = HttpUtil.postJson(fullUrl, null, body);
        LibLibBaseResponse<Map<String, String>> response = JSON.parseObject(string, new TypeReference<LibLibBaseResponse<Map<String, String>>>() {
        });
        if (response.getCode() != 0) {
            throw new BizRuntimeException(response.getMsg());
        }
        return response.getData().get("generateUuid");
    }


    /**
     * 查询生图状态
     *
     * @param generateUuid
     * @return
     */
    public LibLibGenerateStatusResponse status(String generateUuid) {
        String fullUrl = generateFullUrl(Uri.status);

        Map<String, String> params = new HashMap<>();
        params.put("generateUuid", generateUuid);

        String string = HttpUtil.postJson(fullUrl, null, params);
        log.debug("liblib响应结果：'{}'", string);
        LibLibBaseResponse<LibLibGenerateStatusResponse> response = JSON.parseObject(string, new TypeReference<LibLibBaseResponse<LibLibGenerateStatusResponse>>() {
        });
        if (response.getCode() != 0) {
            throw new BizRuntimeException(response.getMsg());
        }
        return response.getData();
    }


    private String generateFullUrl(String uri) {
        String Timestamp = String.valueOf(System.currentTimeMillis());
        String SignatureNonce = RandomStringUtils.randomAlphanumeric(10);
        String signature = LiblibSignUtil.makeSign(secretKey, uri, Timestamp, SignatureNonce);
        Map<String, String> map = new HashMap<>();
        map.put("AccessKey", accessKey);
        map.put("Signature", signature);
        map.put("Timestamp", Timestamp);
        map.put("SignatureNonce", SignatureNonce);
        return HttpUtil.buildUrl(getUrl(uri), map);
    }


}